<template>
    <z-paging
        ref="paging"
        :refresher-out-rate="0.8"
        :show-empty-view-reload-when-error="false"
        :empty-view-img-style="{ width: '308rpx', height: '308rpx' }"
        empty-view-error-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/1c53b8aed0c74201bb092265803a1d48.png"
        empty-view-img="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/12/987eadb1d50949a0a7e25dbbd99abe30.png"
        empty-view-error-text="暂无数据"
        safe-area-inset-bottom
        bg-color="#FFF"
        v-model="dataList"
        @query="queryList"
    >
        <view class="u-page">
            <view class="statistics" @click="goPage">
                <view>
                    <u-text
                        text="最近30天用户增长数量"
                        color="#fff"
                        size="32rpx"
                        :customStyle="{ margin: '30rpx 0 0 104rpx' }"
                    />
                    <u-text
                        :text="`${moreCustomersThanLastMonth}人`"
                        color="#fff"
                        size="48rpx"
                        bold
                        :customStyle="{ margin: '20rpx 0 0 104rpx' }"
                    />
                </view>
            </view>
            <view>
                <view
                    class="weatWrap flex_wrap row_between-column_center"
                    v-if="courseList.length"
                >
                    <u-text
                        text="业务员课程"
                        color="#3D3D3D"
                        size="36rpx"
                        bold
                    />
                    <u-text
                        text="更多"
                        color="#333"
                        size="28rpx"
                        align="right"
                        suffixIcon="arrow-right"
                        iconStyle="fontSize:30rpx;lineHeight:38rpx;color:#333333"
                        @click="goPageDetail(null, 0)"
                    />
                </view>
                <view
                    class="weatWrap flex_wrap row_between-column_center"
                    style="overflow-x: scroll"
                >
                    <view v-for="(item, index) in courseList" :key="index">
                        <view
                            class="videoBox"
                            @click="goPageDetail(item, 1)"
                            :key="index"
                        >
                            <image
                                :src="item.videoCover"
                                mode="aspectFit"
                            ></image>
                            <view class="box">
                                <view class="iconBox"></view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view>
                <view class="weatWrap flex_wrap row_between-column_center">
                    <u-text
                        text="朋友圈海报"
                        color="#3D3D3D"
                        size="36rpx"
                        bold
                    />
                    <u-text
                        text="更多"
                        color="#333"
                        size="28rpx"
                        align="right"
                        suffixIcon="arrow-right"
                        iconStyle="fontSize:30rpx;lineHeight:38rpx;color:#333333"
                        @click="goto"
                    />
                </view>
                <view
                    class="weatWrap flex_wrap row_between-column_center"
                    style="overflow-x: scroll"
                >
                    <view v-for="(item, index) in bannerList" :key="index">
                        <image
                            :src="item"
                            @click="more_counselling(item)"
                            mode="widthFix"
                            style="
                                width: 158rpx;
                                height: auto;
                                margin-right: 20rpx;
                            "
                        ></image>
                    </view>
                </view>
            </view>

            <u-sticky bgColor="#fff">
                <u-tabs
                    :list="list1"
                    @click="click"
                    :activeStyle="{
                        color: '#3D3D3D',
                        fontSzie: '56rpx',
                        fontWeight: '800',
                        transform: 'scale(1.05)',
                    }"
                    :inactiveStyle="{
                        color: '#606266',
                        fontSzie: '46rpx',
                        transform: 'scale(1)',
                    }"
                ></u-tabs>
                <view
                    class="u-demo-block"
                    v-for="item in dataList"
                    :key="item.id"
                >
                    <view class="u-demo-block__content">
                        <view class="album">
                            <view class="album__avatar">
                                <image
                                    src="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/16/7fab9966118946a5904ab3c664b50210.png"
                                    mode=""
                                    style="width: 32px; height: 32px"
                                ></image>
                            </view>
                            <view class="album__content">
                                <u--text
                                    text="十蜂健康"
                                    type="primary"
                                    bold
                                    size="17"
                                ></u--text>
                                <u--text
                                    margin="10rpx 0 8px 0"
                                    :text="item.videoIntro"
                                    @click="goToDetail(item)"
                                ></u--text>
                                <u-album
                                    :urls="item.videoCover"
                                    multipleSize="90"
                                ></u-album>
                            </view>
                        </view>
                    </view>
                    <view class="shareWrap flex_wrap row_between-column_center">
                        <view v-if="item.infoDetail">
                            <text>{{
                                formatMsgTime(item.infoDetail.shareTime)
                            }}</text>
                            <text>{{ item.infoDetail.postName }}</text>
                            <text>{{ item.infoDetail.salesmanName }}</text>
                            <text>分享过</text>
                        </view>
                        <view v-else style="width: 50%"></view>
                        <view>
                            <u-button
                                type="primary"
                                text="一键获客"
                                shape="circle"
                                size="small"
                                color="#3c9cff"
                                @click="shareFun(item)"
                            ></u-button>
                        </view>
                    </view>
                    <u-gap height="4" bgColor="#eee"></u-gap>
                </view>
            </u-sticky>
        </view>
        <u-popup
            :show="showShare"
            mode="bottom"
            @close="showShare = false"
            @open="showShare = true"
            closeOnClickOverlay
            :closeable="true"
            @touchmove.stop.prevent="() => {}"
        >
            <view class="shareBox flex_wrap">
                <view
                    class="flex_wrap flex_column itemBox"
                    @click="downloadImgsFun"
                >
                    <u-icon
                        name="download"
                        size="50"
                        labelPos="bottom"
                        space="10"
                    />
                    <view>下载</view>
                </view>
                <view class="flex_wrap flex_column itemBox">
                    <button open-type="share" style="background: transparent">
                        <u-icon
                            name="/static/images/card/weixin.png"
                            size="50"
                            labelPos="bottom"
                            space="10"
                        />
                        <view>微信好友</view>
                    </button>
                </view>
            </view>
        </u-popup>
    </z-paging>
</template>

<script>
import { baseUrl } from "@/config/tendIdConfig";
import {
    checkHowManyMoreCustomersThanLastWeek,
    getCustomersWithOneClick,
} from "@/api/operate";
import { videoTypeTree ,getVideoCounselling} from "@/api/enterprise.js";
import { mapGetters } from "vuex";
import { wxSaveAuth, downloadImgs } from "@/utils/index";
let shareItem = {};
export default {
    data() {
        return {
            list1: [
                {
                    name: "推荐",
                },
            ],
            bannerList: [],
            courseList: [],
            showShare: false,
            dataList: [],
            moreCustomersThanLastMonth: 0,
			clickTypeId:''
        };
    },
    computed: {
        ...mapGetters(["userInfo", "authority"]),
    },
    onShareAppMessage(res) {
        this.getCustomersWithOneClickFun();
        return {
            title: "十蜂健康资讯",
            desc: "",
            path: "/pages_operate/detail/index?id=" + shareItem.id,
            imageUrl: shareItem.videoCover[0],
        };
    },
	onLoad() {
		this.videoTypeTreeList()
	},
    methods: {
		async videoTypeTreeList(){
			const params = {
				parentId: 0,
				typeModule: "2"
			};
			const res = await videoTypeTree(params);
			this.list1 =  [{
				typeModule: "2",
				id: '',
				name: "推荐",
			}].concat(res.data.map(item => {
			  const { typeName, ...rest } = item;
			  return {
				...rest,
				name: typeName
			  };
			}));
		},
        shareFun(item) {
            this.showShare = true;
            shareItem = item;
        },
        // 下载
        async downloadImgsFun() {
            const urls = shareItem.videoCover;
            // 获取保存到相册权限
            wxSaveAuth().then(async (res) => {
                // 保存多张图片到相册
                await downloadImgs(urls);
                uni.showToast({
                    title: "正在复制文案",
                    duration: 3000,
                });
                uni.setClipboardData({
                    data: shareItem.videoIntro,
                    success() {
                        uni.showToast({
                            title: "复制成功",
                        });
                    },
                    fail() {
                        uni.showToast({
                            title: "复制失败",
                        });
                    },
                });
                this.getCustomersWithOneClickFun();
            });
        },
        // 一键获客
        getCustomersWithOneClickFun() {
            getCustomersWithOneClick({
                salesmanId: this.$store.getters?.userInfo.id,
                winTheCustomerId: shareItem.id,
            });
        },
        async getList(pageNum, pageSize, recordType) {
			const params = {
			    pageNum,
			    pageSize,
			    recordType,
			};
			if(this.clickTypeId && recordType === 2) params.videoTypeId = this.clickTypeId
			const results = await getVideoCounselling(params)
			const result = results.data?.rows ?? [];
			if (recordType === 3)
			    return (this.bannerList = result.map(
			        (v) => v.videoCover
			    ));
			if (recordType === 2) {
			    result.forEach((element) => {
			        element.videoCover = element.videoCover.split(",");
			        element.infoDetail &&
			            (element.infoDetail = JSON.parse(
			                element.infoDetail
			            ));
			    });
			    this.$refs.paging.complete(result);
			}
        },
        getTeachPageVideoList(pageNum, pageSize, recordType) {
            const token =
                this.$store.getters?.customer_token ||
                uni.getStorageSync("customer_token");
            const that = this;
            uni.request({
                url: baseUrl + "/customer/video_info_customer/teachPageVideo",
                method: "POST",
                header: {
                    Authorization: token,
                },
                data: {
                    pageNum,
                    pageSize,
                    recordType,
                    videoDiversity: 1,
                },
                success(res) {
                    if ([991, 992, 401].includes(res.data.code)) {
                        uni.$u.toast(res.data.msg);
                        that.$store.commit("SET_LOGOUT");
                        uni.navigateTo({
                            url: "/pages/user/phone/indexApp",
                        });
                        return;
                    }
                    const result = res.data.data?.rows ?? [];
                    that.courseList = result;
                },
            });
        },
        tabChange(name) {
            this.$store.commit("SET_CURRENT_TAB_NAME", name);
        },
        click(item) {
			console.log(item,'霍克')
			this.clickTypeId = item.id
			// 新闻推荐 recordType 2
			this.$refs.paging.reload();
		},
        more_counselling(item) {
            uni.navigateTo({
                url: `/pages_operate/poster/index?image=${item}`,
            });
        },
        goToDetail(item) {
            uni.navigateTo({
                url: `/pages_operate/detail/index?id=${item.id}`,
            });
        },
        goPage() {
            uni.navigateTo({
                url: "/pages_operate/userdata/index",
            });
        },
        goto() {
            uni.navigateTo({
                url: "/pages_operate/morePoster/index",
            });
        },
        goPageDetail(item, type) {
            const url = type
                ? "/pages_operate/videoPage/detail?videoSeries=" +
                  item.videoSeries
                : "/pages_operate/videoPage/moreVideo";
            uni.navigateTo({
                url: url,
            });
        },
        queryList(pageNum, pageSize) {
            // 增长数量
            checkHowManyMoreCustomersThanLastWeek(this.userInfo.id).then(
                (res) =>
                    (this.moreCustomersThanLastMonth =
                        res?.data?.moreCustomersThanLastMonth ?? 0)
            );
            // 业务员课程 recordType 5
            this.getTeachPageVideoList(1, 4, 5);
            // 海报 recordType 3
            this.getList(1, 6, 3);
            // 新闻推荐 recordType 2
            this.getList(pageNum, pageSize, 2);
        },
        formatMsgTime(timespan) {
            var dateTime = new Date(timespan); // 将传进来的字符串或者毫秒转为标准时间
            var year = dateTime.getFullYear();
            var month = dateTime.getMonth() + 1;
            var day = dateTime.getDate();
            var hour = dateTime.getHours();
            var minute = dateTime.getMinutes();
            // var second = dateTime.getSeconds()
            var millisecond = dateTime.getTime(); // 将当前编辑的时间转换为毫秒
            var now = new Date(); // 获取本机当前的时间
            var nowNew = now.getTime(); // 将本机的时间转换为毫秒
            var milliseconds = 0;
            var timeSpanStr;
            milliseconds = nowNew - millisecond;
            if (milliseconds <= 1000 * 60 * 1) {
                // 小于一分钟展示为刚刚
                timeSpanStr = "刚刚";
            } else if (
                1000 * 60 * 1 < milliseconds &&
                milliseconds <= 1000 * 60 * 60
            ) {
                // 大于一分钟小于一小时展示为分钟
                timeSpanStr = Math.round(milliseconds / (1000 * 60)) + "分钟前";
            } else if (
                1000 * 60 * 60 * 1 < milliseconds &&
                milliseconds <= 1000 * 60 * 60 * 24
            ) {
                // 大于一小时小于一天展示为小时
                timeSpanStr =
                    Math.round(milliseconds / (1000 * 60 * 60)) + "小时前";
            } else if (
                1000 * 60 * 60 * 24 < milliseconds &&
                milliseconds <= 1000 * 60 * 60 * 24 * 15
            ) {
                // 大于一天小于十五天展示位天
                timeSpanStr =
                    Math.round(milliseconds / (1000 * 60 * 60 * 24)) + "天前";
            } else if (
                milliseconds > 1000 * 60 * 60 * 24 * 15 &&
                year === now.getFullYear()
            ) {
                timeSpanStr = month + "-" + day + " " + hour + ":" + minute;
            } else {
                timeSpanStr =
                    year + "-" + month + "-" + day + " " + hour + ":" + minute;
            }
            return timeSpanStr;
        },
    },
};
</script>
<style lang="scss" scoped>
.u-page {
    box-sizing: border-box;
    background-color: #fff;
}

.weatWrap {
    padding: 0 36rpx;
    margin-bottom: 40rpx;
}

.bannerWrap {
    padding: 36rpx;
    box-sizing: border-box;
    display: flex;
    overflow-x: scroll;
}

.album {
    @include flex;
    align-items: flex-start;

    &__content {
        margin-left: 10px;
        flex: 1;
    }
}

.u-demo-block__content {
    padding: 36rpx 36rpx 0 36rpx;
}

.shareWrap {
    padding-left: 100rpx;
    box-sizing: border-box;
    margin: 10rpx;
    padding-right: 40rpx;

    text {
        margin: 10rpx 5rpx;
        margin: 0rpx 10rpx 20rpx 0;
        font-size: 24rpx;
        color: #666666;
    }
}

.statistics {
    width: 678rpx;
    height: 192rpx;
    background: url("https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/18/c603af09a80c4e53ab63a48fc9f6cc4e.png")
        no-repeat;
    opacity: 1;
    color: #fff;
    border-radius: 24rpx 24rpx 24rpx 24rpx;
    margin: 40rpx auto;
    font-size: 32rpx;
    background-size: contain;
}

.shareBox {
    // height: 220rpx;
    padding-bottom: 220rpx;
    .itemBox {
        flex: 1;
        justify-content: center;
        align-items: center;
        padding-top: 50rpx;
        view {
            font-size: 28rpx;
            color: #3d3d3d;
            margin-top: 10rpx;
        }
    }
}
.videoBox {
    width: 470rpx;
    height: 264rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    margin-right: 20rpx;
    position: relative;
    image {
        width: 100%;
        height: 100%;
    }
    .box {
        width: 470rpx;
        height: 264rpx;
        border-radius: 16rpx 16rpx 16rpx 16rpx;
        position: absolute;
        top: 0;
        left: 0;
        background: rgba(0, 0, 0, 0.2);
        .iconBox {
            width: 76rpx;
            height: 76rpx;
            background-image: url(https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/26/9213c9113ad34df6b80ecda7346dd543.png);
            background-size: contain;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    }
}
</style>
